package com.cloud.cmt.usermanage.dict;

import com.cloud.cmt.usermanage.dict.entity.Dictionary;
import com.cloud.cmt.usermanage.dict.util.DictData;
import com.cloud.cmt.usermanage.service.DictionaryRepository;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: wcy
 * Date: 2017/2/16
 * Time: 16:01
 */
@Component
public class DictInitContext implements ApplicationListener<ContextRefreshedEvent> {


    @Resource
    DictionaryRepository dictionaryRepository;

    private static boolean isStart = false;

    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent() == null) {
            if(!isStart) {
                isStart = true;
                initDict();
            }
        }
    }

    public void initDict(){
        try {
            Map term = new HashMap();
            term.put("parent_code", "-1");
            dictionaryRepository.findAll();
            Iterable<Dictionary> list = dictionaryRepository.findAll();
            list.forEach(dict -> {
                DictData.setDicNodeMap(dict.getDicCode(),dict);
                List<Dictionary> chrens = dictionaryRepository.findByParentCode(dict.getDicCode());
                DictData.setDicMap(dict.getDicCode(), chrens);
                chrens.forEach(node ->{
                    DictData.setDicNodeMap(node.getDicCode(),node);
                });
            });

            System.out.println("初始化字典完成。。。");
        }catch (Exception ex){
            System.out.println("初始化字典失败。。。");
            ex.printStackTrace();
        }
    }
}
